/**
 * 状态管理器调试面板
 * 用于展示和测试状态持久化功能
 */

import React, { useState } from 'react';
import { useRoomStateManager } from '../hooks/useRoomStateManager';
import { RoomStatus } from '../../../types/room';

interface StateManagerDebugPanelProps {
  visible?: boolean;
  onClose?: () => void;
}

const StateManagerDebugPanel: React.FC<StateManagerDebugPanelProps> = ({
  visible = false,
  onClose,
}) => {
  const stateManager = useRoomStateManager();
  const [selectedDate, setSelectedDate] = useState<string>(
    new Date().toISOString().split('T')[0].replace('-', '/').substring(5) // MM/DD格式
  );

  if (!visible) return null;

  const allStates = stateManager.exportAllStates();
  const stateCount = Object.keys(allStates).reduce((total, roomId) => {
    return total + Object.keys(allStates[roomId]).length;
  }, 0);

  const statistics = stateManager.getStatistics(selectedDate);

  const handleClearAll = () => {
    if (confirm('确定要清除所有状态数据吗？这将重置所有房间状态。')) {
      stateManager.importStates({});
    }
  };

  const handleExportData = () => {
    const data = stateManager.exportAllStates();
    const blob = new Blob([JSON.stringify(data, null, 2)], {
      type: 'application/json',
    });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `room-states-${new Date().toISOString().split('T')[0]}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  return (
    <div
      style={{
        position: 'fixed',
        top: '10px',
        right: '10px',
        width: '350px',
        maxHeight: '400px',
        backgroundColor: 'white',
        border: '1px solid #ddd',
        borderRadius: '8px',
        padding: '16px',
        boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
        zIndex: 1000,
        fontSize: '12px',
        overflow: 'auto',
      }}
    >
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          marginBottom: '12px',
        }}
      >
        <h3 style={{ margin: 0, fontSize: '14px', color: '#333' }}>
          🔧 状态管理器调试
        </h3>
        {onClose && (
          <button
            onClick={onClose}
            style={{
              background: 'none',
              border: 'none',
              fontSize: '16px',
              cursor: 'pointer',
              color: '#999',
            }}
          >
            ✕
          </button>
        )}
      </div>

      <div style={{ marginBottom: '12px' }}>
        <div style={{ marginBottom: '8px' }}>
          <strong>📊 总体状态：</strong>
        </div>
        <div style={{ color: '#666', lineHeight: '1.4' }}>
          • 存储的状态数量:{' '}
          <span style={{ color: '#2196f3', fontWeight: 'bold' }}>
            {stateCount}
          </span>
          <br />• 最后更新:{' '}
          <span style={{ color: '#4caf50' }}>
            {new Date(stateManager.lastUpdate).toLocaleTimeString()}
          </span>
          <br />• 加载状态:{' '}
          {stateManager.isLoading ? '🔄 正在加载' : '✅ 已完成'}
        </div>
      </div>

      <div style={{ marginBottom: '12px' }}>
        <div style={{ marginBottom: '8px' }}>
          <strong>📅 日期统计：</strong>
        </div>
        <input
          type='text'
          value={selectedDate}
          onChange={e => setSelectedDate(e.target.value)}
          placeholder='MM/DD'
          style={{
            width: '100%',
            padding: '4px 8px',
            border: '1px solid #ddd',
            borderRadius: '4px',
            marginBottom: '8px',
          }}
        />
        <div style={{ fontSize: '11px', lineHeight: '1.4' }}>
          {Object.entries(statistics).map(([status, count]) => {
            if (count === 0) return null;
            const config = getStatusConfig(status as RoomStatus);
            return (
              <div key={status} style={{ marginBottom: '2px' }}>
                <span style={{ marginRight: '4px' }}>{config.icon}</span>
                <span style={{ color: config.color }}>
                  {config.label}
                </span>: <strong>{count}</strong>
              </div>
            );
          })}
        </div>
      </div>

      <div style={{ marginBottom: '12px' }}>
        <div style={{ marginBottom: '8px' }}>
          <strong>🏠 房间状态详情：</strong>
        </div>
        <div
          style={{
            maxHeight: '120px',
            overflow: 'auto',
            fontSize: '10px',
            backgroundColor: '#f9f9f9',
            padding: '6px',
            borderRadius: '4px',
          }}
        >
          {Object.keys(allStates).length === 0 ? (
            <div style={{ color: '#999', textAlign: 'center', padding: '8px' }}>
              暂无状态数据
            </div>
          ) : (
            Object.entries(allStates).map(([roomId, dateStatusMap]) => (
              <div key={roomId} style={{ marginBottom: '6px' }}>
                <div style={{ fontWeight: 'bold', color: '#333' }}>
                  房间 {roomId}:
                </div>
                {Object.entries(dateStatusMap).map(([date, status]) => {
                  const config = getStatusConfig(status);
                  return (
                    <div
                      key={date}
                      style={{
                        marginLeft: '8px',
                        color: '#666',
                        display: 'flex',
                        justifyContent: 'space-between',
                      }}
                    >
                      <span>{date}</span>
                      <span style={{ color: config.color }}>
                        {config.icon} {config.label}
                      </span>
                    </div>
                  );
                })}
              </div>
            ))
          )}
        </div>
      </div>

      <div
        style={{
          display: 'flex',
          gap: '8px',
          flexWrap: 'wrap',
        }}
      >
        <button
          onClick={handleExportData}
          style={{
            flex: 1,
            padding: '6px 12px',
            backgroundColor: '#4caf50',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            cursor: 'pointer',
            fontSize: '11px',
          }}
        >
          📥 导出数据
        </button>
        <button
          onClick={handleClearAll}
          style={{
            flex: 1,
            padding: '6px 12px',
            backgroundColor: '#f44336',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            cursor: 'pointer',
            fontSize: '11px',
          }}
        >
          🗑️ 清除数据
        </button>
      </div>
    </div>
  );
};

// 简化的状态配置获取函数
function getStatusConfig(status: RoomStatus) {
  const configs: Record<
    RoomStatus,
    { icon: string; label: string; color: string }
  > = {
    [RoomStatus.AVAILABLE]: { icon: '🟢', label: '可用', color: '#4caf50' },
    [RoomStatus.BOOKED]: { icon: '🔵', label: '已预订', color: '#2196f3' },
    [RoomStatus.OCCUPIED]: { icon: '🟡', label: '已入住', color: '#ff9800' },
    [RoomStatus.CHECKED_OUT]: { icon: '⚫', label: '已退房', color: '#666' },
    [RoomStatus.CLEANING]: { icon: '🟤', label: '清洁中', color: '#8d6e63' },
    [RoomStatus.MAINTENANCE]: { icon: '🔴', label: '维护中', color: '#f44336' },

    // 其他状态使用默认配置
    [RoomStatus.PARTIALLY_BOOKED]: {
      icon: '🔷',
      label: '部分预订',
      color: '#03a9f4',
    },
    [RoomStatus.VIP_BOOKED]: { icon: '🌟', label: 'VIP预订', color: '#ffc107' },
    [RoomStatus.DIRTY]: { icon: '🟫', label: '待清洁', color: '#795548' },
    [RoomStatus.CLEANED]: { icon: '✨', label: '已清洁', color: '#4caf50' },
    [RoomStatus.DEEP_CLEANING]: {
      icon: '🧼',
      label: '深度清洁',
      color: '#607d8b',
    },
    [RoomStatus.INSPECTING]: { icon: '🔍', label: '检查中', color: '#9c27b0' },
    [RoomStatus.ROUTINE_MAINTENANCE]: {
      icon: '🔧',
      label: '例行维护',
      color: '#ff5722',
    },
    [RoomStatus.DEEP_MAINTENANCE]: {
      icon: '⚙️',
      label: '深度维护',
      color: '#e91e63',
    },
    [RoomStatus.OUT_OF_ORDER]: { icon: '❌', label: '停用', color: '#000' },
    [RoomStatus.REPAIR]: { icon: '🔨', label: '维修中', color: '#795548' },
    [RoomStatus.EQUIPMENT_REPLACEMENT]: {
      icon: '🔄',
      label: '设备更换',
      color: '#607d8b',
    },
    [RoomStatus.LOCKED]: { icon: '🔒', label: '锁定', color: '#424242' },
    [RoomStatus.TEMPORARILY_UNAVAILABLE]: {
      icon: '⏸️',
      label: '临时不可用',
      color: '#9e9e9e',
    },
  };

  return configs[status] || { icon: '❓', label: '未知', color: '#999' };
}

export default StateManagerDebugPanel;
